﻿using ZeroSum.Domain.Entities;

namespace ZeroSum.Domain.Repositories;

/// <summary>
///     通过实体进行查询
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class QueryByEntity<TEntity> : IQuery<TEntity>
    where TEntity : IEntity
{
    private QueryByEntity(Func<IQueryable<TEntity>, IQueryable<TEntity>> query)
    {
        Query = query;
    }

    public Func<IQueryable<TEntity>, IQueryable<TEntity>> Query { get; }

    /// <summary>
    ///     分页操作， 返回一个新的query，不影响原来的Query
    /// </summary>
    /// <param name="page"></param>
    /// <param name="size"></param>
    /// <returns></returns>
    public IQuery<TEntity> Paged(int page, int size)
    {
        var offset = (page - 1) * size;
        var pagedQuery =
            new Func<IQueryable<TEntity>, IQueryable<TEntity>>(query => Query(query).Skip(offset).Take(size));
        return new QueryByEntity<TEntity>(pagedQuery);
    }

    /// <summary>
    ///     工厂方法
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public static QueryByEntity<TEntity> Of(Func<IQueryable<TEntity>, IQueryable<TEntity>> query)
    {
        return new QueryByEntity<TEntity>(query);
    }

    /// <summary>
    ///     创建默认Query（可用于直接查所有数据）
    /// </summary>
    /// <returns></returns>
    public static QueryByEntity<TEntity> Of()
    {
        return new QueryByEntity<TEntity>(query => query);
    }
}